import { defineStore } from 'pinia';
import { reactive } from 'vue';
import { useMapStore } from './map';
import { useCargoStore, type DirectionType } from './cargo';
import { useGameStore } from './game';
export type KeywordCodeType =
  | 'ArrowLeft'
  | 'ArrowRight'
  | 'ArrowUp'
  | 'ArrowDown';

interface Player {
  x: number;
  y: number;
}

export const usePlayerStore = defineStore('player', () => {
  const player = reactive<Player>({
    x: 1,
    y: 1,
  });
  // 将判断是否为墙的操作放在useMapStore里，【不询问对象的状态，而直接告诉它做什么】
  const { isWall } = useMapStore();
  const { cargoMoves } = useCargoStore();
  const { detectionGameCompleted } = useGameStore();

  function _move(key: 'x' | 'y', moveValue: number, direction: DirectionType) {
    let newValue = player[key] + moveValue;
    const position = { ...player, [key]: newValue };
    if (isWall(position)) return;

    // 箱子移动方法，如果箱子能移动会返回true，不能移动就返回false
    const cargoMove = cargoMoves[direction];
    if (!cargoMove(position)) return;

    player[key] = newValue;

    detectionGameCompleted();
  }

  function movePlayerToLeft() {
    _move('x', -1, 'left');
  }

  function movePlayerToRight() {
    _move('x', 1, 'right');
  }

  function movePlayerToUp() {
    _move('y', -1, 'up');
  }

  function movePlayerToDown() {
    _move('y', 1, 'down');
  }

  const operations: { [key in KeywordCodeType]: () => void } = {
    ArrowLeft: movePlayerToLeft,
    ArrowRight: movePlayerToRight,
    ArrowUp: movePlayerToUp,
    ArrowDown: movePlayerToDown,
  };

  return {
    player,
    operations,
    movePlayerToLeft,
    movePlayerToRight,
    movePlayerToUp,
    movePlayerToDown,
  };
});
